package com.atguigu.tingshu.common.config.minio;

import com.atguigu.tingshu.common.annotation.MinioOn;
import com.atguigu.tingshu.common.execption.GuiguException;
import com.atguigu.tingshu.common.service.impl.FileUpLoadServiceImpl;
import io.minio.BucketExistsArgs;
import io.minio.MakeBucketArgs;
import io.minio.MinioClient;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.boot.context.properties.EnableConfigurationProperties;
import org.springframework.context.annotation.Bean;
import org.springframework.context.annotation.Configuration;

@Configuration
@EnableConfigurationProperties(MinioConstantProperties.class)
@MinioOn
public class MinioClientConfiguration {

    //拿一个logger对象
    private final Logger logger = LoggerFactory.getLogger(MinioClientConfiguration.class);

    @Autowired
    private MinioConstantProperties minioProperties;

    @Bean
    public MinioClient minioClient() {
        try {
            MinioClient minioClient =
                    MinioClient.builder()
                            .endpoint(minioProperties.getEndpointUrl())
                            .credentials(minioProperties.getAccessKey(), minioProperties.getSecretKey())
                            .build();

            boolean found =
                    minioClient.bucketExists(BucketExistsArgs.builder().bucket(minioProperties.getBucketName()).build());
            if (!found) {
                minioClient.makeBucket(MakeBucketArgs.builder().bucket(minioProperties.getBucketName()).build());
            } else {
                logger.info("桶已经存在");
            }
            return minioClient;
        } catch (Exception e) {
            logger.error("Error occurred: {}", e.getMessage());
            throw new GuiguException(201, "MinioClient创建失败");
        }
    }

    @Bean
    public FileUpLoadServiceImpl fileUpLoadServiceImpl() {
        return new FileUpLoadServiceImpl();
    }

}

